import React from "react";
import api from "src/http/api";
import { EntityProps, Field } from "src/utils/interface";

import {
  Drawer,
  Descriptions,
  Tag,
  Spin,
  Typography,
  Table,
  TableProps,
} from "antd";

const { useEffect, useState, memo } = React;

interface Props {
  entityName: string;
  visible: boolean;
  onClose: () => void;
}

const EntityInfoDrawer: React.FC<Props> = (props) => {
  const [data, setData] = useState({} as EntityProps);

  const spinning =
    props.entityName && data?.entityName !== props.entityName ? true : false;

  const descriptions = [
    {
      label: "Name",
      key: "entityName",
      value: data.entityName,
    },
    {
      label: "Owners",
      key: "owners",
      value: (
        <div style={{ color: "#1890ff", cursor: "pointer" }}>
          {data.owners?.join(" ")}
        </div>
      ),
    },
    {
      label: "Description",
      key: "description",
      value: data.description,
    },
  ];

  const tableProps: TableProps<Field> = {
    rowKey: "idc",
    loading: data.fields?.length === 0,
    dataSource: data.fields,
    bordered: true,
    columns: [
      {
        title: "Name",
        dataIndex: "name",
      },
      {
        title: "Type",
        dataIndex: "type",
        render: (value, record) => <Tag color="blue">{value}</Tag>,
      },
      {
        title: "Description",
        dataIndex: "description",
      },
      {
        title: "Codec",
        dataIndex: "codec",
      },
    ],
    expandable: {
      childrenColumnName: "innerFields",
      defaultExpandAllRows: true,
      rowExpandable: (record) =>
        record.type === "struct" ||
        record.itemType === "struct" ||
        record.itemType2 === "struct",
    },
  };

  useEffect(() => {
    api.getEntityByEntityName(props.entityName).then((res: any) => {
      setData(res.data);
    });
  }, [props.entityName]);

  return (
    <Drawer
      title="Entity Info"
      placement="right"
      width={500}
      onClose={props.onClose}
      visible={props.visible}
    >
      <Spin spinning={spinning} tip="loading...">
        <Descriptions title="Basic Info" column={1}>
          {descriptions.map((item) => (
            <Descriptions.Item label={item.label} key={item.key}>
              {item.value}
            </Descriptions.Item>
          ))}
        </Descriptions>
        <Typography.Title level={5} style={{ fontWeight: 700 }}>
          Field
        </Typography.Title>
        <Table {...tableProps} />
      </Spin>
    </Drawer>
  );
};

export default memo(EntityInfoDrawer);
